<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>食物管理</title>
    <link rel="stylesheet" th:href="@{/css/style.css}">
</head>
<body>
    <header>
        <h1>个人健康管理系统</h1>
        <nav>
            <ul>
                <li><a th:href="@{/}">首页</a></li>
                <li><a th:href="@{/foods}" class="active">食物管理</a></li>
                <li><a th:href="@{/users}">用户管理</a></li>
                <li><a th:href="@{/dietplans}">膳食计划</a></li>
                <li><a th:href="@{/userhealthindices}">健康指标</a></li>
            </ul>
        </nav>
    </header>

    <main class="container">
        <h2>食物管理</h2>

        <!-- 添加食物表单 -->
        <h3>添加新食物</h3>
        <form id="addFoodForm" action="/api/foods" method="post">
            <div class="form-group">
                <label for="addName">名称:</label>
                <input type="text" id="addName" name="name" required>
            </div>
            <div class="form-group">
                <label for="addCategory">类别:</label>
                <input type="text" id="addCategory" name="category" required>
            </div>
            <div class="form-group">
                <label for="addCalories">卡路里:</label>
                <input type="number" id="addCalories" name="calories" step="0.01" required>
            </div>
            <div class="form-group">
                <label for="addProtein">蛋白质:</label>
                <input type="number" id="addProtein" name="protein" step="0.01" required>
            </div>
            <div class="form-group">
                <label for="addFat">脂肪:</label>
                <input type="number" id="addFat" name="fat" step="0.01" required>
            </div>
            <div class="form-group">
                <label for="addCarbohydrates">碳水化合物:</label>
                <input type="number" id="addCarbohydrates" name="carbohydrates" step="0.01" required>
            </div>
            <div class="form-group">
                <label for="addDescription">描述:</label>
                <input type="text" id="addDescription" name="description">
            </div>
            <button type="submit" class="btn">添加食物</button>
        </form>

        <!-- 食物列表 -->
        <h3>所有食物</h3>
        <table id="foodTable">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>名称</th>
                    <th>类别</th>
                    <th>卡路里</th>
                    <th>蛋白质</th>
                    <th>脂肪</th>
                    <th>碳水化合物</th>
                    <th>描述</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <!-- 食物数据将通过JavaScript加载 -->
            </tbody>
        </table>

        <!-- 编辑食物表单 (初始隐藏) -->
        <h3 id="editFormTitle" style="display: none;">编辑食物</h3>
        <form id="editFoodForm" style="display: none;" action="" method="put">
            <input type="hidden" id="editId" name="id">
            <div class="form-group">
                <label for="editName">名称:</label>
                <input type="text" id="editName" name="name" required>
            </div>
            <div class="form-group">
                <label for="editCategory">类别:</label>
                <input type="text" id="editCategory" name="category" required>
            </div>
            <div class="form-group">
                <label for="editCalories">卡路里:</label>
                <input type="number" id="editCalories" name="calories" step="0.01" required>
            </div>
            <div class="form-group">
                <label for="editProtein">蛋白质:</label>
                <input type="number" id="editProtein" name="protein" step="0.01" required>
            </div>
            <div class="form-group">
                <label for="editFat">脂肪:</label>
                <input type="number" id="editFat" name="fat" step="0.01" required>
            </div>
            <div class="form-group">
                <label for="editCarbohydrates">碳水化合物:</label>
                <input type="number" id="editCarbohydrates" name="carbohydrates" step="0.01" required>
            </div>
            <div class="form-group">
                <label for="editDescription">描述:</label>
                <input type="text" id="editDescription" name="description">
            </div>
            <button type="submit" class="btn">保存更改</button>
            <button type="button" class="btn btn-danger" onclick="hideEditForm()">取消</button>
        </form>

    </main>

    <footer>
        <p>&copy; 2025 个人健康管理系统</p>
    </footer>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            fetchFoods();

            // 处理添加食物表单提交
            document.getElementById('addFoodForm').addEventListener('submit', function(event) {
                event.preventDefault();
                const formData = new FormData(event.target);
                const foodData = Object.fromEntries(formData.entries());

                fetch('/api/foods', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(foodData)
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不佳');
                    }
                    return response.json();
                })
                .then(() => {
                    fetchFoods(); // 刷新列表
                    event.target.reset(); // 重置表单
                })
                .catch(error => console.error('添加食物失败:', error));
            });

            // 处理编辑食物表单提交
            document.getElementById('editFoodForm').addEventListener('submit', function(event) {
                event.preventDefault();
                const foodId = document.getElementById('editId').value;
                const formData = new FormData(event.target);
                const foodData = Object.fromEntries(formData.entries());

                fetch(`/api/foods/${foodId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(foodData)
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不佳');
                    }
                    return response.json();
                })
                .then(() => {
                    fetchFoods(); // 刷新列表
                    hideEditForm(); // 隐藏编辑表单
                })
                .catch(error => console.error('更新食物失败:', error));
            });
        });

        function fetchFoods() {
            fetch('/api/foods')
                .then(response => response.json())
                .then(foods => {
                    const tbody = document.querySelector('#foodTable tbody');
                    tbody.innerHTML = ''; // 清空现有内容
                    foods.forEach(food => {
                        const row = tbody.insertRow();
                        row.innerHTML = `
                            <td>${food.id}</td>
                            <td>${food.name}</td>
                            <td>${food.category}</td>
                            <td>${food.calories}</td>
                            <td>${food.protein}</td>
                            <td>${food.fat}</td>
                            <td>${food.carbohydrates}</td>
                            <td>${food.description || ''}</td>
                            <td>
                                <button class="btn" onclick="editFood(${food.id})">编辑</button>
                                <button class="btn btn-danger" onclick="deleteFood(${food.id})">删除</button>
                            </td>
                        `;
                    });
                })
                .catch(error => console.error('获取食物列表失败:', error));
        }

        function editFood(id) {
            fetch(`/api/foods/${id}`)
                .then(response => response.json())
                .then(food => {
                    document.getElementById('editId').value = food.id;
                    document.getElementById('editName').value = food.name;
                    document.getElementById('editCategory').value = food.category;
                    document.getElementById('editCalories').value = food.calories;
                    document.getElementById('editProtein').value = food.protein;
                    document.getElementById('editFat').value = food.fat;
                    document.getElementById('editCarbohydrates').value = food.carbohydrates;
                    document.getElementById('editDescription').value = food.description || '';
                    
                    document.getElementById('editFormTitle').style.display = 'block';
                    document.getElementById('editFoodForm').style.display = 'block';
                })
                .catch(error => console.error('获取食物详情失败:', error));
        }

        function hideEditForm() {
            document.getElementById('editFormTitle').style.display = 'none';
            document.getElementById('editFoodForm').style.display = 'none';
            document.getElementById('editFoodForm').reset();
        }

        function deleteFood(id) {
            if (confirm('确定要删除此食物吗？')) {
                fetch(`/api/foods/${id}`, {
                    method: 'DELETE'
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不佳');
                    }
                    fetchFoods(); // 刷新列表
                })
                .catch(error => console.error('删除食物失败:', error));
            }
        }
    </script>
</body>
</html> 